package service

import (
	"aiRole/internal/dao/model"
	"aiRole/internal/dao/query"
	"aiRole/internal/dto/request"
	result "aiRole/internal/dto/reslult"
	initSystem "aiRole/pkg/init"
	"aiRole/pkg/util"
	"context"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
)

type RoleService struct {
}

// RoleList **后期改为分页查询
func (s RoleService) RoleList(c *gin.Context) {
	roleDB := query.Use(initSystem.DB).Character
	list, err := roleDB.WithContext(c).Find()
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, list)
}

func (s RoleService) SaveRole(c *gin.Context, req request.RoleRequest) {
	value, exists := c.Get("userinfo")
	if !exists {
		initSystem.Logger.Error("用户信息不存在")
		result.Error(c, 500, "用户信息不存在")
		return
	}
	userInfo := value.(model.User)
	fmt.Println(userInfo)
	roleDB := query.Use(initSystem.DB).Character
	info, err := roleDB.WithContext(context.Background()).Where(roleDB.Name.Eq(req.Name)).First()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	if info != nil {
		result.Error(c, 500, "角色已存在")
		return
	}
	var role model.Character
	role.Name = req.Name
	role.Description = req.Description
	role.AvatarURL = req.AvatarUrl
	role.Prompt = req.Prompt
	role.CreatedBy = userInfo.ID
	err = roleDB.WithContext(c).Create(&role)
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, "")
}

func (s RoleService) SearchRole(c *gin.Context, text string) {
	roleDB := query.Use(initSystem.DB).Character
	list, err := roleDB.WithContext(c).Where(roleDB.Name.Like("%"+text+"%")).Select(roleDB.ID, roleDB.Name, roleDB.Description).Find()
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, list)
}

func (s RoleService) AnswerQuestion(c *gin.Context) {
	question := c.Query("question")
	characterIDStr := c.Query("character_id")
	if characterIDStr == "" {
		result.Error(c, 400, "角色ID不能为空")
		return
	}
	characterID, err := strconv.ParseInt(characterIDStr, 10, 64)
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 400, "角色ID格式错误")
		return
	}
	// 查询角色的提示词
	roleDB := query.Use(initSystem.DB).Character
	role, err := roleDB.WithContext(c).Where(roleDB.ID.Eq(characterID)).First()
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	call := util.NewAiCall()
	answer, err := call.ChatCompletion([]request.Message{
		{
			Role:    "system",
			Content: role.Prompt,
		},
		{
			Role:    "user",
			Content: question,
		},
	}, "gpt-oss-120b")
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, answer)
}

func (s RoleService) TellStory(c *gin.Context) {
	topic := c.Query("topic")
	characterIDStr := c.Query("character_id")
	if characterIDStr == "" {
		result.Error(c, 400, "角色ID不能为空")
		return
	}
	characterID, err := strconv.ParseInt(characterIDStr, 10, 64)
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 400, "角色ID格式错误")
		return
	}
	// 查询角色的提示词
	roleDB := query.Use(initSystem.DB).Character
	role, err := roleDB.WithContext(c).Where(roleDB.ID.Eq(characterID)).First()
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	call := util.NewAiCall()
	story, err := call.ChatCompletion([]request.Message{
		{
			Role:    "system",
			Content: role.Prompt,
		},
		{
			Role:    "user",
			Content: topic,
		},
	}, "gpt-oss-120b")
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, story)
}

func (s RoleService) SaveSkill(c *gin.Context, req request.SkillSaveRequest) {
	skillDB := query.Use(initSystem.DB).CharacterSkill
	var saveDto model.CharacterSkill
	saveDto.CharacterID = req.CharacterId
	saveDto.Name = req.Name
	saveDto.Description = req.Description
	saveDto.CreatedBy = 0
	saveDto.Prompt = req.Prompt
	err := skillDB.WithContext(c).Create(&saveDto)
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, "保存成功")
}

func (s RoleService) DeleteRole(c *gin.Context, id string) {
	roleDB := query.Use(initSystem.DB).Character
	//无法将 'id' (类型 string) 用作类型 int64
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 400, "角色ID格式错误")
		return
	}
	_, err = roleDB.WithContext(c).Where(roleDB.ID.Eq(idInt)).Delete()
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, "删除成功")
}

func (s RoleService) SkillList(c *gin.Context, id int64) {
	skillDB := query.Use(initSystem.DB).CharacterSkill
	list, err := skillDB.WithContext(c).Where(skillDB.CharacterID.Eq(id)).Omit(skillDB.Prompt).Find()
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, list)

}

func (s RoleService) ById(c *gin.Context, id string) {
	roleDB := query.Use(initSystem.DB).Character
	//无法将 'id' (类型 string) 用作类型 int64
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 400, "角色ID格式错误")
		return
	}
	role, err := roleDB.WithContext(c).Where(roleDB.ID.Eq(idInt)).First()
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, role)
}
